﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinqToLfsWorld.Interface;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace LinqToLfsWorld.Serialization
{

	/// <summary>
	/// Serializes and deserializes an object to and from XML.
	/// </summary>
	public class XmlSerializer<T> : ISerializer<T>
		where T : class
	{

		/// <summary>
		/// Gets the serializer.
		/// </summary>
		/// <value>The serializer.</value>
		protected DataContractSerializer Serializer
		{
			get
			{
				if (_Serializer == null)
					_Serializer = new DataContractSerializer(typeof(T), SerializationTypes.KnownTypes);
				return _Serializer;
			}
		}
		private DataContractSerializer _Serializer = null;

		#region ISerializer<ILfsWorldEntity> Members

		/// <summary>
		/// Serializes the specified object graph.
		/// </summary>
		/// <param name="objectGraph">The object graph.</param>
		public string Serialize(T objectGraph)
		{
			StringWriter writer = new StringWriter();

			using (XmlWriter xmlWriter = XmlWriter.Create(writer))
			{
				Serializer.WriteObject(xmlWriter, objectGraph);
			}

			return writer.ToString();
		}

		/// <summary>
		/// Deserializes the specified serialized object graph.
		/// </summary>
		/// <param name="serialized">The serialized object graph.</param>
		public T Deserialize(string serialized)
		{
			StringReader reader = new StringReader(serialized);
			T outputObject = default(T);

			using (XmlReader xmlReader = XmlReader.Create(reader))
			{
				outputObject = Serializer.ReadObject(xmlReader) as T;
			}

			return outputObject;
		}

		#endregion
	}
}
